package com.wangtianxiang.sql.generator;

import com.wangtianxiang.sql.generator.domain.SqlFile;
import com.wangtianxiang.sql.generator.domain.SqlTemplate;
import com.wangtianxiang.sql.generator.loader.data.DataSourceLoader;
import com.wangtianxiang.sql.generator.loader.data.YmlDataSourceLoader;
import com.wangtianxiang.sql.generator.loader.template.TemplateSourceLoader;
import com.wangtianxiang.sql.generator.loader.template.XmlTemplateSourceLoader;
import com.wangtianxiang.sql.generator.utils.FileUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class GeneratorContext {

    private final Map<String,Object> dataContext = new ConcurrentHashMap<String,Object>(16);
    private final List<SqlFile> sqlFiles = new ArrayList<>();
    private final List<DataSourceLoader> dataSourceLoaders = new ArrayList<>();
    private final List<TemplateSourceLoader> templateSourceLoaders = new ArrayList<>();
    private String path = "template";

    public GeneratorContext(String path) {
        this.path = path;
        initDataSourceLoader();
        initTemplateSourceLoader();
        loadDataSource();
        loadTemplateSource(dataContext);
        generatorSqlFile();
    }

    private void initDataSourceLoader(){
        dataSourceLoaders.add(new YmlDataSourceLoader());
    }

    private void loadDataSource(){
        dataSourceLoaders.forEach(sourceLoader -> dataContext.putAll(sourceLoader.load()));
    }

    private void initTemplateSourceLoader(){
        templateSourceLoaders.add(new XmlTemplateSourceLoader(path));
    }

    private void loadTemplateSource(Map<String,Object> dataContext){
        templateSourceLoaders.forEach(sourceLoader -> sqlFiles.addAll(sourceLoader.load(dataContext)));
    }

    private void generatorSqlFile(){
        sqlFiles.forEach(sqlFile -> {
            StringBuilder sb = new StringBuilder();
            Iterator<SqlTemplate> sqlTemplates = sqlFile.getSqlTemplateMap().values().iterator();
            while(sqlTemplates.hasNext()){
                sb.append(sqlTemplates.next().getSql().toString());
            }
            FileUtils.writeFile(sb.toString(),sqlFile.getOutPutPath());
        });
    }

}
